<script setup lang="ts">
import { busListStore } from '@/stores'
import { useMemberStore } from '@/stores/modules/member'
import type { ApplyBusiness } from '@/types/business'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { KpcodeBarcodeDueEntity, PanicReservationBarcodeRequest } from '@/types/code'
import { getBarcodeDuePageAPI, getBarcodeDueMyPageAPI, getPanicReservationBarcodeAPI, postOrderStatusAPI, getReservationBarcodeCountAPI } from '@/api/code'
import NoList from '@/components/NoList.vue'
import { getDistance } from '@/utils/utils'

const busStore = busListStore()
const profile = ref<ApplyBusiness>({})
const id = ref('')
const user = useMemberStore().profile

const getLocation = async () => {
  uni.getSystemInfo({
    success(res) {
      let locationEnabled = res.locationEnabled //判断手机定位服务是否开启
      let locationAuthorized = res.locationAuthorized //判断定位服务是否允许微信授权
      if (locationEnabled == false || locationAuthorized == false) {
        //手机定位服务（GPS）未授权
        uni.showModal({
          title: '授权',
          content: '获取授权失败，是否前往授权？',
          success: function (result) {
            if (result.confirm) {
              uni.openAppAuthorizeSetting()
            }
          },
          fail: function () {
            uni.showToast({
              title: '请前往设置中授权位置信息',
              icon: 'none',
            })
          },
        })
      } else {
        uni.chooseLocation({
          success: function (response) {
            // console.log('位置信息:', response)
            // response对象信息
            // latitude: 39.85856
            // longitude: 116.28616
            lat.value = response.latitude
            lng.value = response.longitude
            getBarcodeDuePage()
            getBarcodeDueMyPage()
          },
        })
      }
    },
  })
}
const lat = ref(0)
const lng = ref(0)

// 获取预约列表
const list = ref<KpcodeBarcodeDueEntity[]>([])
const getBarcodeDuePage = async () => {
  const res = await getBarcodeDuePageAPI(profile.value.areaCode!)
  console.log(res.data)

  list.value = res.data.records
  list.value.map((item) => {
    item.dis = getDistance(lat.value, lng.value, Number(item.lat), Number(item.lng))
  })
}

// 获取我的预约列表
const listMy = ref<KpcodeBarcodeDueEntity[]>([])
const getBarcodeDueMyPage = async () => {
  let id = busStore.busList[0].id
  const res = await getBarcodeDueMyPageAPI(id)
  listMy.value = res.data.records
  listMy.value.map((item) => {
    item.dis = getDistance(lat.value, lng.value, Number(item.lat), Number(item.lng))
  })
}

// 获取抢单数量
let totalNum = ref('0')

const getReservationBarcodeCount = async () => {
  const urlStr = `?busId=${busStore.busList[0].id}&status=2`
  const res = await getReservationBarcodeCountAPI(urlStr)
  if (res.data) {
    totalNum.value = res.data as string
  }
}

onLoad(() => {
  if (!useMemberStore().profile) {
    uni.navigateTo({ url: '/pages/login/login' })
  } else {
    id.value = useMemberStore().profile.userId
    profile.value = busStore.busList[0]
    getLocation()
  }
  getReservationBarcodeCount()
})

// 取消订单
const cancelOrder = async (id: any) => {
  const res = await postOrderStatusAPI({ id: id, status:'0' })
  uni.showToast({ icon: 'success', title: '取消订单成功' })
  getBarcodeDuePage()
  getBarcodeDueMyPage()
}
// 抢单
const form = ref<PanicReservationBarcodeRequest>({})
const getlOrder = async (id:string) => {
  form.value.id = id
  form.value.agentId = busStore.busList[0].id
  form.value.agentName = busStore.busList[0].name
  form.value.agentPhone = busStore.busList[0].contactsPhone
  const res = await getPanicReservationBarcodeAPI(form.value)
  uni.showToast({ icon: 'success', title: '抢单成功' })
  getBarcodeDuePage()
  getBarcodeDueMyPage()
}

// 送达
const doneOrder = async (id: any) => {
  const res = await postOrderStatusAPI({ id: id, status:'2' })
  uni.showToast({ icon: 'success', title: '订单配送成功' })
  getBarcodeDuePage()
  getBarcodeDueMyPage()
}
</script>
<template>
  <!-- 个人资料 -->
  <view class="profile">
    <!-- 情况1：已登录 -->
    <view class="overview" v-if="true">
      <navigator url="/pagesMember/profile/profile" hover-class="none">
        <image class="avatar" mode="aspectFill" :src="user.avatar"></image>
      </navigator>
      <view class="meta">
        <view class="nickname"> {{ user.nickname || user.name }} </view>
        <text class="update">{{ user.phone }}</text>
      </view>
      <div class="num">接单数量：{{ totalNum }}</div>
    </view>
    <!-- 情况2：未登录 -->
    <view class="overview" v-else>
      <navigator url="/pages/login/login" hover-class="none">
        <image
          class="avatar gray"
          mode="aspectFill"
          src="http://yjy-xiaotuxian-dev.oss-cn-beijing.aliyuncs.com/picture/2021-04-06/db628d42-88a7-46e7-abb8-659448c33081.png"
        ></image>
      </navigator>
      <view class="meta">
        <navigator url="/pages/login/login" hover-class="none" class="nickname"> 未登录 </navigator>
        <view class="extra">
          <text class="tips">点击登录账号</text>
        </view>
      </view>
    </view>
  </view>
  <view class="list">
    <view class="title">我的抢单</view>
    <template v-if="listMy.length>0">
      <navigator
        :url="'/pages/codeDetail/codeResDetail?id='+item.id"
        class="order"
        v-for="item in listMy"
        :key="item.id"
      >
        <view class="top">
          <text class="name">{{ item.busName }}</text>
          <view class="distance">
            <uni-icons type="location" size="12"></uni-icons>
            {{item.dis.toFixed(1)}}km
          </view>
        </view>
        <view class="left">
          <view class="middle">
            <view class="num">卷数：{{ item.resNo }}</view>
            <view class="phone"><uni-icons type="phone" size="12"></uni-icons>拨打电话</view>
          </view>
        </view>
        <button v-if="item.status == '2'" size="mini" disabled>完成</button>
        <button v-if="item.status == '3' || item.status == '4'" size="mini" disabled>已取消</button>
        <button v-if="item.status == '1'" size="mini" style="color: #fff; background-color: #26b99c" @tap.stop="doneOrder(item.id)">送达</button>
        <button v-if="item.status == '1'" size="mini" class="cancle" @tap.stop="cancelOrder(item.id)">取消</button>
      </navigator>
     </template>
    <no-list v-else />
  </view>

  <!-- 预约列表 -->
  <view class="list yuyue">
    <view class="title">预约列表</view>
    <template v-if="list.length > 0">
      <navigator :url="'/pages/codeDetail/codeResDetail?id='+item.id" class="order" v-for="item in list" :key="item.id">
        <view class="top">
          <text class="name">{{ item.busName }}</text>
          <view class="distance">
            <uni-icons type="location" size="12"></uni-icons>
            {{item.dis.toFixed(1)}}km
          </view>
        </view>
        <view class="left">
          <view class="middle">
            <view class="num">卷数：{{ item.resNo }}</view>
            <view class="phone"><uni-icons type="phone" size="12"></uni-icons>拨打电话</view>
          </view>
        </view>
        <button size="mini" style="color: #fff; background-color: #26b99c" @tap.stop="getlOrder(item.id!)">抢单</button>
      </navigator>
    </template>
    <no-list v-else />
  </view>
</template>

<style lang="scss">
/* 用户信息 */
.profile {
  padding: 40rpx 0;
  position: relative;
  background-color: rgb(0, 206, 170);

  .overview {
    display: flex;
    height: 120rpx;
    padding: 0 36rpx;
    align-items: flex-end;
    justify-content: space-between;
    color: #fff;
    .num {
      margin-bottom: 20rpx;
      font-size: 26rpx;
      align-self: flex-end;
    }
  }

  .avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .gray {
    filter: grayscale(100%);
  }

  .meta {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    line-height: 30rpx;
    padding: 16rpx 0;
    margin-left: 20rpx;
    flex: 1;
  }

  .nickname {
    max-width: 350rpx;
    margin-bottom: 16rpx;
    font-size: 30rpx;

    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .tips {
    font-size: 22rpx;
  }

  .update {
    padding: 3rpx 10rpx 1rpx;
    color: rgba(255, 255, 255, 0.8);
    border: 1rpx solid rgba(255, 255, 255, 0.8);
    margin-right: 10rpx;
    border-radius: 30rpx;
    font-size: 20rpx;
  }
}
.list {
  .title {
    display: flex;
    justify-content: space-between;
    padding-right: 5px;
    align-items: center;
    padding-left: 15px;
    height: 40px;
    background-color: #26b99c;
    font-weight: normal;
    color: #fff;
    font-size: 14px;
  }
  .order {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    align-items: center;
    border-bottom: 1px solid #eee;
    padding: 15px;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      margin-bottom: 5px;
      .name {
        font-size: 30rpx;
      }
      .distance {
        font-size: 24rpx;
        color: #26b99c;
      }
    }
    .left {
      flex: 1;
      .middle {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        .num {
          margin-right: 20px;
        }
      }
    }
    button {
      width: 60px;
      padding: 0;
      margin-left: 5px;
    }
    .cancle {
      color: #fff;
      background-color: #e43d33;
    }
  }
}
.yuyue {
  padding-bottom: 40px;
}
</style>
